package com.lepu.app.fun.chat.activity;

import java.util.HashMap;
import java.util.Map;
import java.util.Timer;
import java.util.TimerTask;

import org.json.JSONException;
import org.json.JSONObject;

import android.annotation.SuppressLint;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.InputFilter;
import android.text.TextUtils;
import android.view.View;
import android.view.inputmethod.InputMethodManager;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.app.config.AppConfig;
import com.app.utils.AppEnterTongJi;
import com.app.utils.Const;
import com.app.utils.LoginUtil;
import com.app.utils.Setting;
import com.core.lib.application.BaseFragmentActivity;
import com.core.lib.core.ApiClient;
import com.core.lib.utils.EmojiFilter;
import com.core.lib.utils.main.UIHelper;
import com.core.lib.widget.MyDialog;
import com.core.lib.core.AsyncRequest;
import com.eyzhs.app.R;
import com.lepu.app.fun.hospital.HospitalExpertInfoActivity;
import com.lepu.app.fun.hospital.HospitalExpertStateActivity;
import com.lepu.app.fun.mother_circle.MotherPubContentActivity;
import com.lepu.app.main.activity.AppBroswerActivity;
import com.lepu.app.widget.CustomTopBarNew;
import com.lepu.app.widget.CustomTopBarNew.OnTopbarNewLeftLayoutListener;

public class OnlineActivity extends BaseFragmentActivity implements OnTopbarNewLeftLayoutListener,
		CustomTopBarNew.OnTopbarNewRightButtonListener, AsyncRequest {

	private static final String REQUEST_DATA = "request_data";

	private EditText mEditText;
    private int mType = 1;
	
	private static final int SUCCESS = 200;
	private static final int FAIL = 201;
	private String mRequestContent;

	private static OnlineActivity mInstance = null;
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.chat_online_activity);
		
		mInstance = this;
		AppEnterTongJi.clickEvent(59, "");
		init();
	}

	@Override
	public void onDestroy() {
		super.onDestroy();
		
		mInstance = null;
	}

	public static OnlineActivity getInstance(){
		return mInstance;
	}
	
	/**
	 * 添加页面动画，需要重写这个方法，
	 */
	@Override
	public void onBackPressed() {
		saveDraft();
		finish(true);
	}

	@Override
	public void onTopbarLeftLayoutSelected() {
		saveDraft();
		finish(true);
	}

	@Override
	public void onTopbarRightButtonSelected() {
		Intent intent = new Intent(this, HospitalExpertInfoActivity.class);
		startActivityAnim(intent, R.anim.lib_push_down_up_in, R.anim.lib_push_down_up_out);
	}
	
	/**
	 * 初始化方法
	 */
	private void init() {
		// topbar
		CustomTopBarNew topbar = (CustomTopBarNew) findViewById(R.id.topbar);
		topbar.setRightText("专家介绍");
		topbar.setonTopbarNewLeftLayoutListener(this);
		topbar.setOnTopbarNewRightButtonListener(this);
		
		mEditText = (EditText) findViewById(R.id.edit_submit_request);
		mEditText.setFilters(new InputFilter[] { new EmojiFilter(),new InputFilter.LengthFilter(400) });
		mEditText.setText(AppConfig.getConfigString(OnlineActivity.this, Const.CONFIG_HOSPITAL_CONTENT, ""));
		
		mType = (int) getIntent().getIntExtra("type", 1);
		int ConsultPrice = getIntent().getIntExtra("ConsultPrice", 0);
		
		if(mType == 2){
			topbar.setTopbarTitle("儿科问诊");
		}else if(mType == 1){
			topbar.setTopbarTitle("妇产科问诊");
		}
		
		TextView tipTextView = (TextView) findViewById(R.id.tipTextView);
		tipTextView.setText(String.format("每次咨询需300金币，现优惠期消耗%d金币", ConsultPrice));
		
		ImageView tipCloseImageView = (ImageView) findViewById(R.id.tipCloseImageView);
		tipCloseImageView.setOnClickListener(new View.OnClickListener() {
			
			@Override
			public void onClick(View v) {
				
				RelativeLayout tipLayout = (RelativeLayout) findViewById(R.id.tipLayout);
				tipLayout.setVisibility(View.GONE);
			}
		});
		
		Button saveButton = (Button) findViewById(R.id.saveButton);
		saveButton.setOnClickListener(new View.OnClickListener() {
			
			@Override
			public void onClick(View arg0) {

				mRequestContent = mEditText.getText().toString();
				if (TextUtils.isEmpty(mRequestContent)) {
					UIHelper.showToast(OnlineActivity.this, "描述内容不能为空");
				} else if (mRequestContent.length() < 10) {
					UIHelper.showToast(OnlineActivity.this, "请输入10个汉字以上的症状内容。");
				} else {
					request(mRequestContent);
					showProgressDialog();
				}
			
			}
		});
		
		showEdit();
	}


	//请求数据
	public void request(String sendData) {

		String url = Setting.updateQuestionUrl();

		Map<String, Object> map = new HashMap<String, Object>();
		JSONObject params = new JSONObject();
		try {
			params.put("DeviceID", Setting.DEVICEID);
			params.put("ApplicationID", Setting.APPLICATIONID);
			params.put("UserID", LoginUtil.getUserId());
			params.put("LoginToken", LoginUtil.getLoginToken());

			params.put("Category", mType);
			params.put("QuestionID", "");
			params.put("Question", sendData);
			map.put("ht", params);
			
		} catch (Exception e) {
		}
		
		ApiClient.http_post(url, map, null, this, REQUEST_DATA, false,false,false);
	}


	@SuppressLint("HandlerLeak")
	private Handler mHandler = new Handler() {
		public void handleMessage(Message msg) {
			switch (msg.what) {
			case SUCCESS:
				hideProgressDialog();
				cleanDraft();
				Intent intent = new Intent(OnlineActivity.this, HospitalExpertStateActivity.class);
				startActivityAnim(intent, R.anim.lib_push_down_up_in, R.anim.lib_push_down_up_out);
				
				break;
			case FAIL:
				hideProgressDialog();
				break;
			default:
				break;

			}
		}
	};
	
	private void dowithScore(String message) {
		MyDialog dialog = new MyDialog(this)
				.setMessage(message)
				.setNegativeButton(R.string.ele_hospital_button_know,
						R.drawable.btn_cancel_selector, R.color.color_white,
						new View.OnClickListener() {

							@Override
							public void onClick(View v) {

							}
						})
				.setPositiveButton(R.string.ele_hospital_button_go_score,
						R.drawable.btn_ok_selector, R.color.color_white,
						new View.OnClickListener() {

							@Override
							public void onClick(View v) {
								// 去赚积分
								// 跳转到 积分规则页面
								Intent intent = new Intent(OnlineActivity.this,AppBroswerActivity.class);
								intent.putExtra("title", "规则");
								intent.putExtra("url", Setting.getJifenRuleUrl());
								startActivity(intent, true);
							}
						});

		dialog.create(null);
		dialog.showMyDialog();
	}

    //弹出键盘
	public void showEdit(){
		Timer timer = new Timer();
		timer.schedule(new TimerTask() {

			public void run() {
				InputMethodManager inputManager = (InputMethodManager) mEditText
						.getContext().getSystemService(Context.INPUT_METHOD_SERVICE);
				inputManager.showSoftInput(mEditText, 0);
			}

		}, 1000);
	}
	
	//保存草稿箱
	private void saveDraft(){
		String contentContent = mEditText.getText().toString().trim();
		AppConfig.setConfig(OnlineActivity.this, Const.CONFIG_HOSPITAL_CONTENT, contentContent);
	}
	
	private void cleanDraft(){
		AppConfig.setConfig(OnlineActivity.this, Const.CONFIG_HOSPITAL_CONTENT, "");
	}
	
	@Override
	public void RequestComplete(Object object, Object data) {
		if (object.equals(REQUEST_DATA)) {
			Message msg = mHandler.obtainMessage();
			msg.what = SUCCESS;
			mHandler.sendMessage(msg);
		} 
	}

	@Override
	public void RequestError(Object object, int errorId, final String errorMessage) {
		if (object.equals(REQUEST_DATA)) {
			runOnUiThread(new Runnable() {
				@Override
				public void run() {
					hideProgressDialog();

					int code = 0;
					String message = "";
					try {
						JSONObject jsonObject = new JSONObject(errorMessage);
						JSONObject obj1 = (JSONObject) jsonObject.get("Result");
						code = obj1.optInt("Status");
						message = obj1.optString("Message");
					} catch (JSONException e) {
						e.printStackTrace();
					}

					if (code == 213) {
						// 积分不足
						dowithScore(message);
					}

				}
			});
		}
	}

}
